﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ProtocolBuilder
{
    class Protocol
    {
        private XElement xmlElement;

        public string Name
        {
            get
            {
                return this.xmlElement.Attribute("name").Value;
            }
            set
            {
                this.xmlElement.Attribute("name").Value = value;
            }
        }

        public XElement XElement
        {
            get
            {
                return this.xmlElement;
            }
        }

        #region constructer

        public Protocol()
            : this(true)
        { }

        private Protocol(bool initialize)
        {
            if (initialize)
            {
                this.Initialize();
            }
        }

        #endregion

        public void AddPacket(Packet packet)
        {
            this.xmlElement.Add(packet.XElement);
        }

        public IEnumerable<Packet> GetAllPacket()
        {
            IList<Packet> result = new List<Packet>();
            foreach (XElement child in this.xmlElement.Elements("packet"))
            {
                result.Add(Packet.FromXml(child));
            }

            return result;
        }

        public static Protocol FromXml(XElement element)
        {
            if (element == null || element.Name.Equals("protocol"))
            {
                throw new ArgumentException("not a protocol element.");
            }

            Protocol result = new Protocol(false);
            result.xmlElement = element;

            return result;
        }

        private void Initialize()
        {
            this.xmlElement = new XElement("protocol",
                new XAttribute("name", string.Empty));
        }
    }
}
